package com.rd.project.controller;

import com.rd.project.service.UploadService;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import org.apache.commons.io.FilenameUtils;
import org.apache.myfaces.custom.fileupload.UploadedFile;

@ManagedBean(name = "uploadController")
@RequestScoped
public class UploadController {

    @EJB
    private UploadService uploadService;

    private UploadedFile uploadedFile;
    
    private String response = "";

    public UploadedFile getUploadedFile() {
        return uploadedFile;
    }

    public void setUploadedFile(UploadedFile uploadedFile) {
        this.uploadedFile = uploadedFile;
    }

    public void excelOpslaan() throws IOException {
        String fileName = FilenameUtils.getName(uploadedFile.getName());

        File outputFilePath = File.createTempFile(uploadedFile.getName(), "");

        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            inputStream = uploadedFile.getInputStream();
            outputStream = new FileOutputStream(outputFilePath);

            int read = 0;
            final byte[] bytes = new byte[1024];
            while ((read = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }

        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
        if (inputStream != null) {
            inputStream.close();
        }
        uploadService.verwerkExcel(outputFilePath.toString());
        this.response = "Bestand is verwerkt!";
    }

    public String getResponse() {
        return response;
    }

    public void setResponse(String response) {
        this.response = response;
    }
    
    
}
